<template>
	<uni-popup ref="popup" type="bottom" @change="onChange" :safe-area="false" style="z-index: 999;">
		<view class="red-content" :style="{height:systemInfo.screenHeight + 'px'}">
			<!--导航和状态栏-->
			<view :style="{height:statusBarHeight+'px',width:'750rpx',backgroundColor: '#ffffff'}"></view>
			<view class="content-navigation d-flex d-r a-center j-between">
				<view class="navigation-left d-flex d-r a-center j-center" @tap="close">
				    <image src="/static/center/back.png" class="back"></image>
				</view>
				<text class="navigation-title">发红包</text>
			    <view class="navigation-right">
			        <!-- <view @tap="openSt" class="st_btn" v-if="type!=='pick'&&VER.ver">声明与文献</view> -->
			    </view>
			</view>
			<view @tap="showType" class="content-type d-flex d-r a-center">
				<text class="content-type-title">{{typeArray[type]}}</text>
				<image style="width: 24rpx;height: 24rpx;" src="/static/nvue/more-lower.png"></image>
			</view>
			<!--
			<view class="content-row">
				<view @tap="showType" class="row-info d-flex d-r a-center j-between">
					<text class="info-left">红包类型</text>
					<view class="info-right d-flex d-r a-center j-end">
						<text class="info-right-type">{{typeArray[type]}}</text>
						<image style="width: 24rpx;height: 24rpx;" src="/static/nvue/more-2.png"></image>
					</view>
				</view>
			</view>
			-->
			<view class="content-row" v-if="type==0||type==1">
				<view class="row-info d-flex d-r a-center j-between">
					<text class="info-left">红包个数</text>
					<view class="info-right d-flex d-r a-center j-end">
						<input @input="inputNumber" class="info-right-input" type="number" inputmode="numeric" v-model="number" placeholder="填写红包个数"/>
						<text class="info-right-type" style="padding-left: 10rpx;">个</text>
					</view>
				</view>
			</view>
			<view  @tap="showPeoplePopup" class="content-row" v-if="type==2">
				<view class="row-info d-flex d-r a-center j-between">
					<text class="info-left">发给谁</text>
					<view class="info-right d-flex d-r a-center j-end">
						<view v-if="member!=null" class="d-flex d-r a-center j-center">
							<userhead
							    width="80"
							    height="80"
							    :saveKey="member.userId"
							    :isVip="member.isVip"
							    :src="member.userPhoto"
							/>
							<text class="info-right-type" style="padding-left: 10rpx;">{{member.userName}}</text>
						</view>
						<image style="width: 24rpx;height: 24rpx;" src="/static/nvue/more-2.png"></image>
					</view>
				</view>
			</view>
			<view class="content-row">
				<view class="row-info d-flex d-r a-center j-between">
					<text class="info-left">{{amountTitle[type]}}</text>
					<view class="info-right d-flex d-r a-center j-end">
						<input @input="inputAmount" class="info-right-input" type="digit" inputmode="decimal" v-model="amount" placeholder="¥0.00"/>
					</view>
				</view>
			</view>
			<view class="content-row">
				<view class="row-info d-flex d-r a-center j-between">
					<text class="info-left">红包备注</text>
					<view class="info-right d-flex d-r a-center j-end">
						<input v-model="remark" class="info-right-input" placeholder="恭喜发财，大吉大利"/>
					</view>
				</view>
			</view>
			<view class="content-money d-flex d-r a-center j-center">
				<text class="content-money-symbol">￥</text>
				<text class="content-money-number">{{totalMoney}}</text>
				<text class="content-money-unit">元</text>
			</view>
			<view class="content-button d-flex d-r j-center">
				<tm-button
				    _style="margin: 0 auto;font-weight: 600;"
				    :width="690"
				    :height="80"
				    :shadow="-1"
				    :round="5"
				    :linear-color="['#64F1C5', '#29DBA3']"
				    linear="left"
				    :fontSize="32"
				    fontColor="#ffffff"
				    label="塞钱进红包"
					@tap="confirmPayment"
				></tm-button>
			</view>
		</view>
	</uni-popup>
	<!--选择-->
	<uni-popup ref="typePopup" type="bottom" :safe-area="false">
	    <view class="sys-confirm-content">
			<text class="confirm-content-title">请选择红包类型</text>
			<text v-for="(item,index) in typeArray"  @tap="onType(index)" class="content-button button-confirm">{{item}}</text>
			<view style="height: 20rpx; background: #f5f5f5"></view>
			<view @tap="typePopup.close" style="background-color: #FFFFFF;">
				<text  class="content-button" style="color: #999999;" >取消</text>
				<view :style="{height:(systemInfo.screenHeight-systemInfo.safeArea.bottom) + 'px'}"></view>
			</view>
			<!--
			<view :style="{paddingBottom:systemInfo.safeArea.height + 'px'}">
				<text @tap="typePopup.close" class="content-button" style="color: #999999;">取消</text>
			</view>
			-->
	    </view>
	</uni-popup>
	<!--指定领取人-->
	<uni-popup ref="peoplePopup" type="bottom" :safe-area="false" >
		<view class="red-content" :style="{height:systemInfo.screenHeight + 'px'}">
			<view style="background: #ffffff; width: 750rpx;" :style="{ height: systemInfo.statusBarHeight + 'px' }"></view>
			
			<view class="content-navigation d-flex d-r a-center j-between">
				<view class="navigation-left d-flex d-r a-center j-center" @tap="closePeople">
				    <image src="/static/center/back.png" class="back"></image>
				</view>
				<text class="navigation-title">指定领取人</text>
			    <view class="navigation-right">
			        <!-- <view @tap="openSt" class="st_btn" v-if="type!=='pick'&&VER.ver">声明与文献</view> -->
			    </view>
			</view>
			
			<view class="search_box d-flex a-center j-center">
			    <view class="search d-flex d-r a-center">
					<!--
			        <i class="tmicon tmicon-search" style="color: #ccc; font-size: 30rpx" ></i>
					-->
			        <input
			            type="text"
			            class="inp"
			            @input="search"
			            v-model="searchText"
			            placeholder="好友昵称"
			            placeholder-style="color:#ccc;font-size:25rpx;"
			        />
			    </view>
			</view>
			<scroll-view
			    :scroll-y="true"
			    class="content"
			    :style="{ height: `calc(  ${systemInfo.screenHeight}px - ${systemInfo.statusBarHeight}px - 190rpx)` }"
			>
			    <view class="box_view">
			        <view class="list" v-if="groupMembers.length">
			            <view
			                class="psr row d-flex d-r a-center"
			                v-for="m in groupMembers"
			                :key="m.userId"
			                @tap="toggleCheck(m)"
			            >
			                <view class="head_box psr">
			                    <userhead
			                        width="95"
			                        height="95"
			                        :saveKey="m.userId"
			                        :isVip="m.isVip"
			                        :src="m.userPhoto"
			                    />
			                </view>
			                <view class="name d-flex a-center">
			                    <rich-text :nodes="m.nodes"></rich-text>
			                </view>
			                <view class="line"></view>
						
			                <view class="visitor d-flex a-center j-center" v-if="m.role==='Tourist'">游客</view>
			                
			            </view>
			        </view>
						
			        <view class="data-null d-flex d-c a-center" v-if="!groupMembers.length">
			            <image class="data-null-image" mode="widthFix" src="/static/img/nodata.png" alt="" />
			            <text class="data-null-text">竟然什么都没有~</text>
			        </view>
			    </view>
			</scroll-view>  
		</view>
	</uni-popup>
	<confirmPay ref="confirmPopup" @confirmPay="sendRed"></confirmPay>
</template>
<script setup lang="tsx">
import { ref } from 'vue';
import { onLoad } from "@dcloudio/uni-app";
import { getGroupMember,sendGroup } from "@/api/api";
import { getGroupMemberList } from "@/hooks/imHooks";
import { imStore as imStore1 } from "@/store/imStore";
import userhead from "@/components/userhead.vue";
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import BigNumber from "bignumber.js";
import { userData as userDataStore } from "@/store/userData";
import confirmPay from "@/components/confirmPay.vue";

const userData: any = userDataStore();
const imStore: any = imStore1();
const systemInfo: any = systemInfoStore();
//const systemInfo = ref(uni.getSystemInfoSync());
const statusBarHeight = ref(0);
onLoad(() => {
	const res = uni.getWindowInfo();
	statusBarHeight.value  = res.statusBarHeight
	
})
const popup = ref();
const groupId = ref()
const open = (id:string) => {
	//初始化参数
	
	type.value = 1;
	number.value = "";
	amount.value = "";
	member.value = null
	totalMoney.value = "0.00";
	remark.value = ""
	
	groupId.value = id
	popup.value.open();
	//查询群人数
	Promise.all([reqGroupMember(groupId.value)]).then(() => {
	    initData();
	});
}
const close = () => {
	popup.value.close();
}
const onChange = (e:any) => {
	if(e.show){
		// #ifdef APP-PLUS
		let pages = getCurrentPages();
		let page:any = pages[pages.length - 1];
		let currentWebview = page.$getAppWebview()
		currentWebview.setStyle({ popGesture: 'none' })
		// #endif
	}else{
		// #ifdef APP-PLUS
		let pages = getCurrentPages();
		let page:any = pages[pages.length - 1];
		let currentWebview = page.$getAppWebview()
		currentWebview.setStyle({ popGesture: 'close' })
		// #endif
	}
}
const typeArray = ref(["普通红包","拼手气红包","专属红包"])
const amountTitle = ref(["单个金额","总金额","金额"])
const type = ref(1)//红包类型
const number = ref()//红包个数
const amount = ref()//红包金额
const member:any = ref()//红包领取人
const totalMoney = ref("0.00")//总金额
const remark = ref("")//备注
const typePopup = ref()
const showType = () => {
	typePopup.value.open()
}
const onType = (idx:number) => {
	type.value = idx;
	totalAmount()
	typePopup.value.close()
	
}
//-----------------指定领取人相关---------------------
const peoplePopup = ref()
const showPeoplePopup = () => {
	peoplePopup.value.open()
}
const closePeople = () => {
	peoplePopup.value.close();
}
const searchText = ref("");
const groupMembers:any = ref([]);
const all_groupMembers:any = ref([]);
const selected:any = ref({});
const search = (event:any) => {
	searchText.value = event.detail.value;
    if (!searchText.value) {
        initData();
    }else{
		groupMembers.value = all_groupMembers.value.filter((item:any) => {
		    const str = item.remark || item.userName;
		    if (str.toLowerCase().search(searchText.value.toLowerCase()) !== -1) {
		        return true;
		    } else {
		        return false;
		    }
		});
		matchTextHighLight();
	}
};
const initData = () => {
    const friends = imStore.friends;
    all_groupMembers.value.forEach((item:any)=>{
        friends.forEach((f:any)=>{
            if(f.userID === item.userId){
                item.remark = f.remark;
            }
        })
    })

    const clone_groupMembers = JSON.parse(JSON.stringify(all_groupMembers.value));
    
    groupMembers.value = clone_groupMembers.map((item:any) => {
        let color = "#333";
        if (item.isVip) {
            color = "#F19945";
        }

        return {
            ...item,
            nodes: `<div style="color:${color};font-weight:400;">${
                item.remark || item.userName
            }</div>`,
        };
    });
};
const matchTextHighLight = () => {
    const reg = new RegExp(searchText.value, "gi");
    groupMembers.value = groupMembers.value.map((item:any) => {
        const obj = {
            ...item,
        };
        // const str = `<div style="color:#555;">${item.profile.nick}</div>`;
        const str = item.remark || item.userName;
        const nodes = `<div style="color:#555;font-weight:400;">${str.replace(
            reg,
            (s: any) => {
                return `<span style="color:#23e2a6">${s}</span>`;
            }
        )}</div>`;
        obj.nodes = nodes;
        return obj;
    });
};
const reqGroupMember = async (groupId: string) => {
    const res: any = await getGroupMember({ groupId });
    const { flag, data } = res;
    if (flag !== 1) {
        uni.showToast({
            icon: "none",
            title: "获取成员列表失败",
            duration: 1500,
        });
    }
    if(selected.value.userId){
        if(data.list.every((item:any)=>item.userId!==selected.value.userId)){
            selected.value={};
        }
    }
    all_groupMembers.value = data.list.filter((item:any)=>item.userId!==userData.id);
};
const toggleCheck = (m:any) => {
	member.value = m
	peoplePopup.value.close()
}
const confirmPopup = ref()
//         调起支付  
const confirmPayment = () => {
	uni.hideKeyboard()
	//如果未设置支付密码，跳转到支付密码设置
	if(!userData.isPayPwd){
		uni.navigateTo({
			url:`/pages/setPayPwd/setPayPwd`,
			success:() => {
				uni.showToast({
					title:'请先设置支付密码',
					icon:'none',
					duration:1500
				})
			}
		});
		return
	}
   //拼手气红包
   if(type.value == 0 || type.value == 1 ){
		if(number.value==null||number.value==''){
			uni.showToast({
				title:'请输入红包个数',
				icon:'none',
				duration:1500
			})
			return
		}
		if(!isPositiveInteger(number.value)){
			uni.showToast({
				title:'红包个数输入有误',
				icon:'none',
				duration:1500
			})
			return
		}
		
		if(Number(number.value)>(all_groupMembers.value.length+1)){
			uni.showToast({
				title:'红包个数不可大于群人数',
				icon:'none',
				duration:1500
			})
			return
	   }
	   if(amount.value==null||amount.value==''){
			uni.showToast({
				title:'请输入红包金额',
				icon:'none',
				duration:1500
			})
			return
	   }
	   if(!isValidNumber(amount.value)){
			uni.showToast({
				title:'红包金额输入有误',
				icon:'none',
				duration:1500
			})
			return
	   }
	   let product = new BigNumber(number.value).multipliedBy(new BigNumber(0.01)).toNumber();
	   if(Number(totalMoney.value)<product){
			uni.showToast({
				title:'每个红包最少0.01元',
				icon:'none',
				duration:1500
			})
			return
	   }
   }
   if(type.value == 2){
   		if(member.value==null){
			uni.showToast({
				title:'请指定领取人',
				icon:'none',
				duration:1500
			})
			return
		}
		if(amount.value==null||amount.value==''){
			uni.showToast({
				title:'请输入红包金额',
				icon:'none',
				duration:1500
			})
			return
		}
		if(!isValidNumber(amount.value)){
			uni.showToast({
				title:'红包金额输入有误',
				icon:'none',
				duration:1500
			})
			return
		}
   }
   if(remark.value.length>10){
	   uni.showToast({
			title:'备注不可超过10个字',
			icon:'none',
			duration:1500
	   })
	   return
   }
   confirmPopup.value.open()
}
let loadSend = false
const sendRed = (payPwd:string) => {
	confirmPopup.value.close()
	let redRemark = "恭喜发财，大吉大利"
	if(remark.value!=null&&remark.value!='')redRemark = remark.value
	let redNumber = number.value
	if(type.value==2)redNumber = 1
	let param:any = {
		   userId:userData.id,
		   groupId:groupId.value,
		   amount:new BigNumber(totalMoney.value).multipliedBy(new BigNumber(100)).toNumber(),
		   num:redNumber,
		   mode:type.value,
		   payPwd:payPwd,
		   remark:redRemark
	}
	//console.log(member.value.userId)
	if(type.value==2)param.directUserId = member.value.userId
	//console.log(param)
	if(loadSend)return
	loadSend = true
	sendGroup(param).then((res:any) => {
		loadSend = false
		uni.$emit("onSendButton");
		uni.$emit("toBottom");
		if(res.success){
			close()
			uni.showToast({
				title:"发送成功",
				icon:'none',
				duration:1500
			})
		}else{
			uni.showToast({
				title:res.message,
				icon:'none',
				duration:1500
			})
		}
		
	}).catch((error:any) => {  
		loadSend = false
	});
}
//统计红包总金额
const totalAmount = () => {
	if(type.value==0){
		let redNumber = 0;
		if(isPositiveInteger(number.value))redNumber = Number(number.value);
		let redAmount = 0;
		if(isValidNumber(amount.value))redAmount = Number(amount.value);
		let product = new BigNumber(redNumber).multipliedBy(new BigNumber(redAmount)).toNumber();
		totalMoney.value = product.toFixed(2)
	}else{
		let product = 0;
		if(isValidNumber(amount.value))product = Number(amount.value);
		totalMoney.value = product.toFixed(2)
	}
	
}
const inputNumber = (event:any) =>{
	number.value = event.detail.value
	totalAmount()
}
const inputAmount = (event:any) =>{
	amount.value = event.detail.value
	totalAmount()
}
const isPositiveInteger = (value:string) => {  
	const positiveIntegerRegex = /^\d+$/;
	return positiveIntegerRegex.test(value) && parseInt(value, 10) > 0;
}
const isValidNumber = (value:string) => {  
    var regex = /^(0|([1-9]\d*))(\.\d{1,2})?$/;  
	// 如果字符串符合正则表达式，再进行大于等于0.01的判断  
	if (regex.test(value)) {  
		// 将字符串转换为数字进行比较  
		var num = parseFloat(value);  
		return num >= 0.01;  
	}  
	return false; 
}  
defineExpose({
  open,
  close
});
</script>

<style lang="scss" scoped>
.red-content{
	background: #F5F5F5;
	.content-navigation{
		height: 100rpx;
		background-color: #ffffff;
		.navigation-left{
			width: 108rpx;
			height: 100rpx;
			.back{
				width: 48rpx;
				height: 48rpx;
			}
		}
		.navigation-title{
			font-family: PingFangSC, PingFang SC;
			font-weight: 600;
			font-size: 34rpx;
			color: #000000;
		}
		.navigation-right{
			width: 108rpx;
			height: 100rpx;
		}
	}
	.content-type{
		padding: 20rpx 0 0 20rpx;
		.content-type-title{
			padding-right: 10rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 30rpx;
			color: #CFB53B;
		}
	}
	.content-row{
		padding: 20rpx 20rpx 0 20rpx;
		.row-info{
			padding: 0 30rpx;
			width: 710rpx;
			height: 120rpx;
			background: #FFFFFF;
			border-radius: 10rpx;
			.info-left{
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 30rpx;
				color: #333333;
			}
			.info-right{
				min-width: 200rpx;
				.info-right-type{
					padding-right: 10rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 32rpx;
					color: #333333;
				}
				.info-right-icon{
					font-size: 20rpx;
					color: #CCCCCC;
				}
				.info-right-input{
					width: 350rpx;
					text-align: right;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 32rpx;
					color: #333333;
				}
			}
		}
	}
	.content-money{
		padding-top: 60rpx;
		.content-money-symbol{
			padding-right: 10rpx;
			font-family: 'din',DINAlternate-Bold, DINAlternate;
			font-weight: bold;
			font-size: 50rpx;
			color: #333333;
		}
		.content-money-number{
			padding-right: 10rpx;
			font-family: 'din',DINAlternate-Bold, DINAlternate;
			font-weight: bold;
			font-size: 68rpx;
			color: #333333;
		}
		.content-money-unit{
			padding-top: 18rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #333333;
		}
	}
	.content-button{
		width: 750rpx;
		padding-top: 60rpx;
	}
	.search_box {
	    width: 750rpx;
	    background: #fff;
	    padding-bottom: 20rpx;
	
	    .search {
	        width: 690rpx;
	        height: 70rpx;
	        border-radius: 10rpx;
	        background: #f5f5f5;
	        padding: 0 30rpx;
	        .inp {
	            width: 570rpx;
	            margin-left: 20rpx;
	            font-size: 25rpx;
	        }
	    }
	}
	
	.content {
	    background: #f5f5f5;
	    .box_view {
	        margin-top: 20rpx;
	        background: #fff;
	        .title {
	            height: 60rpx;
	            font-size: 28rpx;
	            color: #333;
	            font-weight: 400;
	            padding: 0 30rpx;
	        }
	        .list {
	        }
	        .row {
	            position: relative;
	            padding: 0 30rpx;
	            gap: 20rpx;
	            height: 110rpx;
	            .head_box {
	                width: 95rpx;
	                height: 95rpx;
	                .vip_icon {
	                    width: 97rpx;
	                    height: 43rpx;
	                    bottom: -10rpx;
	                }
	            }
	            .head {
	                width: 95rpx;
	                height: 95rpx;
	                border-radius: 50%;
	                box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.1);
	                border: 3px solid #ffffff;
	            }
	            .name {
	                margin-left: 10rpx;
	                font-size: 34rpx;
	                color: $slim-text5;
	                &:active {
	                }
	            }
	
	            &:active {
	                background: #f5f5f5;
	            }
	            .line {
	                position: absolute;
	                height: 1px;
	                width: 600rpx;
	                left: 130rpx;
	                background-color: #f5f5f5;
	                bottom: 0;
	            }
	            .visitor{
	                position:absolute;
	                right:100rpx;
	                font-size:20rpx;
	                color:#F19945;
	                width: 60rpx;
	            height: 32rpx;
	            background: #FBE9D7;
	            border-radius: 4rpx;
	
	            }
	            .joined {
	                color: #aaa;
	                font-size: 28rpx;
	            }
	            .check_box {
	                width: 40rpx;
	                height: 40rpx;
	                border: 2rpx solid #ddd;
	                right: 30rpx;
	                border-radius: 50%;
	                overflow:hidden;
	                background:#fff;
	                &.checked{
	                    background:#23e2a6;
	                    border: 2rpx solid #23e2a6;
	                }
	                .checkImg {
	                    width: 28rpx;
	                    height: 28rpx;
	                }
	            }
	
	            // &::before {
	            //     content: "";
	            //     position: absolute;
	            //     left: 110rpx;
	            //     right: 20rpx;
	            //     bottom: 0;
	            //     height: 1px;
	            //     background-color: #f5f5f5;
	            // }
	        }
	    }
		.data-null{
			padding-top: 300rpx;
			width: 750rpx;
			background-color: #F5F5F5;
			.data-null-image{
				width: 360rpx;
			}
			.data-null-text{
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #999999;
				text-align: center;
			}
		}
	}
}
/*底部弹出操作确认框样式*/
.sys-confirm-content{
	background: #FFFFFF;
	border-radius: 20rpx 20rpx 0rpx 0rpx;
	
	.confirm-content-title{
		padding-top: 50rpx;
		padding-left: 30rpx;
		padding-right: 30rpx;
		font-size: 32rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 600;
		color: #333333;
	}
	.confirm-content-tip{
		padding: 20rpx 40rpx 20rpx 90rpx;
		.content-tip-row{
			font-size: 30rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
		}
	}
	.content-button{
		height: 100rpx;
		line-height: 100rpx;
		
		text-align: center;
		font-size: 34rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 600;
		
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}
	.button-confirm{
		margin-top: 20rpx;
	}
}


/*     公共属性     */
.psr {
    position: relative;
}

.psa {
    position: absolute;
}

.center {
    text-align: center;
}

.bold {
    font-weight: bold;
}


.a-center {
    align-items: center;
}

.j-center{
    justify-content: center;
}

.j-between {
    justify-content: space-between;
}

.j-around {
    justify-content: space-around;
}


.d-flex {
    display: flex;
}

.d-c {
    flex-direction: column;
    
}
.d-r {
    flex-direction: row !important;
}

.j-end {
    justify-content: flex-end;
}


.wrap {
    flex-wrap: wrap;
}

.nowrap {
    flex-wrap: nowrap;
}

.uline{
    text-decoration: underline;
}

.c_main{
    color:$slim-main;
}

.b_main{
    background-color:$slim-main;
}

</style>